#include "StdAfx.h"
#include "ModelWidget.h"
#include "QModelViewer.h"
ModelWidget::ModelWidget(QWidget* parent, Qt::WindowFlags f)
:	OgreRenderWidget(parent, f), 
	m_pEntity(NULL), m_pEntityNode(NULL)
{

}

ModelWidget::~ModelWidget(void)
{
}

void ModelWidget::createFrameListener()
{
	m_pFrameListener = new OgreRenderFrameListener;
	m_pRoot->addFrameListener(m_pFrameListener);
}

void ModelWidget::loadEntity(const QString& modelPath)
{
	if(m_pEntity)
	{
		m_pFrameListener->setAnimationState(NULL, 1.0f);
		m_pSceneMgr->destroyEntity(m_pEntity);
	}
	if(NULL == m_pEntityNode)
	{
		m_pEntityNode = m_pRootNode->createChildSceneNode();
	}
	m_pEntity = m_pSceneMgr->createEntity(modelPath.toLocal8Bit().data());
	m_pEntityNode->attachObject(m_pEntity);
	const Ogre::MeshPtr& pMesh = m_pEntity->getMesh();
	Ogre::uint32 numMeshes = pMesh->getNumSubMeshes();
	QStringList materialList;
	for(Ogre::int32 i = 0; i < numMeshes; ++i)
	{
		materialList.push_back(QString::fromLocal8Bit(pMesh->getSubMesh(i)->getMaterialName().c_str()));
	}
	m_pModelViewer->setMaterialNames(materialList);	;
	m_pModelViewer->setSkeletonName(QString::fromLocal8Bit(m_pEntity->getMesh().get()->getSkeletonName().c_str()));
	Ogre::AnimationStateSet* pAniSet = m_pEntity->getAllAnimationStates();
	Ogre::AnimationStateIterator itr = pAniSet->getAnimationStateIterator();
	QStringList aniList;
	while(itr.hasMoreElements())
	{
		aniList.push_back(itr.getNext()->getAnimationName().c_str());
	}
	m_pModelViewer->setAnimations(aniList);
}

void ModelWidget::playAnimation(const QString& aniName, bool isLoop /* = false */, Ogre::Real speed /* = 1.0f */)
{
	if(m_pEntity)
	{
		Ogre::AnimationState* pAni = m_pEntity->getAnimationState(aniName.toLocal8Bit().data());
		pAni->setLoop(isLoop);
		m_pFrameListener->setAnimationState(pAni, speed);
	}
}